package main

import (
	"time"

	mqtt "github.com/eclipse/paho.mqtt.golang"
)

// MQTTConfig mqtt configuration
type MQTTConfig struct {
	Broker         string   `json:"broker,omitempty"`
	ClientID       string   `json:"clientId,omitempty"`
	TopicPrefix    string   `json:"topicPrefix,omitempty"`
	PublishTimeout Duration `json:"publishTimeout,omitempty"`
	Qos            int      `json:"qos,omitempty"`
}

// MQTTSender mqtt sender handler
type MQTTSender struct {
	client mqtt.Client
}

// NewMQTTSender create new mqtt sender
func NewMQTTSender(config MQTTConfig) (*MQTTSender, error) {
	opts := mqtt.NewClientOptions().AddBroker(config.Broker).SetClientID(config.ClientID).SetCleanSession(false)
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		return nil, token.Error()
	}
	sender := &MQTTSender{
		client: client,
	}
	return sender, nil
}

// Send send data
func (s *MQTTSender) Send(topic string, qos int, payload []byte, timeout time.Duration) error {
	token := s.client.Publish(topic, byte(qos), false, payload)
	token.WaitTimeout(timeout)
	return token.Error()
}
